/**
 * Copyright (c) Daniel Centore
 *
 * ex: set filetype=java expandtab tabstop=4 shiftwidth=4 :
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * This code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation.
 */
package ronp.anim.kludges;

import java.awt.Point;

import ronp.anim.data.Grip;
import ronp.anim.data.filmstrip.Animation;
import ronp.anim.data.filmstrip.Layer;

/**
 * Handles cropping {@link Animation}s
 * 
 * @author Daniel Centore
 *
 */
public class AutoCrop
{
	/**
	 * Crops an {@link Animation} of all side which never has a grip touch them
	 * @param anim The {@link Animation} to crop
	 */
	public static void autoCrop(Animation anim)
	{
		int frames = anim.countFrames();

		int x = Integer.MAX_VALUE;
		int y = Integer.MAX_VALUE;

		for (Layer l : anim.getLayers())
		{
			Grip g = l.getGrip();
			for (int i = 0; i < frames; i++)
			{
				Point p = g.getPosition(i);
				x = Math.min(x, p.x);
				y = Math.min(y, p.y);
			}
		}

		for (Layer l : anim.getLayers())
		{
			Grip g = l.getGrip();
			for (int i = 0; i < frames; i++)
			{
				if (!g.isEmpty(i))
				{
					Point p = g.getPosition(i);
					g.setPosition(i, new Point(p.x - x, p.y - y));
				}
			}
		}

		int wid = 0;
		int hei = 0;
		for (Layer l : anim.getLayers())
		{
			Grip g = l.getGrip();
			for (int i = 0; i < frames; i++)
			{
				Point p = g.getPosition(i);
				wid = Math.max(wid, p.x);
				hei = Math.max(hei, p.y);
			}
		}

		anim.setWidth(wid);
		anim.setHeight(hei);
	}

}
